package com.zdkj.subway.check.controller.stationTiecketManager.xianWngCJXXQR.shouRuJS;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.annotation.SwCheckNoRepeatSubmitBaseController;
import com.zdkj.subway.check.controller.stationTiecketManager.xianWngCJXXQR.shouRuJS.reportError.TvmReportErrorSqlUpdate;
import com.zdkj.subway.check.controller.stationTiecketManager.xianWngCJXXQR.shouRuJS.reportError.TvmReportErrorUtil;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.*;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.JdbcUtil;
import com.zdkj.subway.check.util.UserInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 线网下的收入结算
 */
@RequestMapping("/xw_js_tvm")
@RestController
@Slf4j
public class Xw_TVM_shouJieSuanCtrl extends SwCheckNoRepeatSubmitBaseController {

    @Resource
    XwShouJieSuanMapper xwShouJieSuanMapper;
    @Resource
    SwStTvmDailyBillCashPayMapper swStTvmDailyBillCashPayMapper;
    @Resource
    SwStTvmIncomeSettleMapper swStTvmIncomeSettleMapper;
    @Resource
    SwAuTvmBoxAmountDifferenceMapper swAuTvmBoxAmountDifferenceMapper;
    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    SwStLongperiodSettleLogMapper swStLongperiodSettleLogMapper;

    @Resource
    private PlatformTransactionManager platformTransactionManager;
    @Resource
    private SwStTvmCheckDetailMapper swStTvmCheckDetailMapper;
    @Resource
    SwStReportErrorAlterAppayMapper swStReportErrorAlterAppayMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 获取结算日期
     * @param param
     * @return
     */
    @RequestMapping("/get_sw_ck_data_submit_date")
    @ApiOperation(value = "获取结算日期", notes = "获取结算日期")
    public Result get_sw_ck_data_submit_date(@RequestParam Map<String,String> param) throws SQLException {
        Result result=new Result(ResultDetailMsg.OK);
        String sql="select date_add(a.END_TIME,interval 1 second) startSettleDate,date_add(a.END_TIME,interval (ifnull(b.TVM_SETTLEMENT_TERM,1)) day) endSettleDate\n" +
                " from SW_CK_DATA_SUBMIT a\n" +
                " left join sw_pm_long_period_settlement b on  a.LINE_CODE = b.LINE_CODE  and a.STATION_CODE = b.STATION_CODE and b.DEL_FLAG = '0'\n" +
                " where  a.LINE_CODE = '"+param.get("lineCode")+"'\n" +
                " and a.STATION_CODE = '"+param.get("stationCode")+"'";
        List<Map<String, Object>> res = JdbcUtil.exeSqlQuery(sql);
        result.setData(res);
        return result;
    }
    /**
     * tvm报表差错待提交主页
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getXw_tvm_shouJieSuan_reportError_waitSubmit")
    @ApiOperation(value = "tvm报表差错待提交主页", notes = "tvm报表差错待提交主页")
    public Page getXw_tvm_shouJieSuan_reportError_waitSubmit(Page page, @RequestParam Map<String,String> param) throws ParseException, SQLException {
        param.put("settleStatus","2");
        List<Map<String,Object>> swStTvmIncomeSettles = swStTvmIncomeSettleMapper.selectSwStTvmIncomeSettle(param);
        List<Map<String, Object>> tvm_shouJieSuan_waitSubmit = new ArrayList<>();
        for(Map<String,Object> map:swStTvmIncomeSettles){
            Map<String,String> p=new HashMap<>();
            p.put("startSettleDate",String.valueOf(map.get("settleStartTime")).replace(".0",""));
            p.put("endSettleDate",String.valueOf(map.get("settleEndTime")).replace(".0",""));
            p.put("lineCode",String.valueOf(map.get("lineCode")));
            p.put("stationCode",String.valueOf(map.get("stationCode")));
            p.put("is_report_settle_status","2");
            p.put("approvalStatus","0");
            p.put("confirmStatus","1");
            p.put("tvmCode",String.valueOf(map.get("tvmCode")));
            //tvm 收入结算待提交
            List<Map<String, Object>> res = TvmReportErrorUtil.getXw_tvm_shouJieSuan_waitSubmit(p);
            tvm_shouJieSuan_waitSubmit.addAll(res);
        }

        page.setData(tvm_shouJieSuan_waitSubmit);
        return page;
    }

    /**
     * TVM收入结算待提交
     * @param page
     * @param param
     * @return
     * @throws SQLException
     */
    @RequestMapping("/getXw_tvm_shouJieSuan_waitSubmit")
    @ApiOperation(value = "TVM收入结算待提交", notes = "TVM收入结算待提交")
    public Page getXw_tvm_shouJieSuan_waitSubmit(Page page, @RequestParam Map<String,String> param) throws SQLException {

//        List<Map<String, Object>> tvm_shouJieSuan_waitSubmit = xwShouJieSuanMapper.getXw_tvm_shouJieSuan_waitSubmit(param);
        List<Map<String, Object>> tvm_shouJieSuan_waitSubmit = TvmUtil.getXw_tvm_shouJieSuan_waitSubmit(param);
        page.setData(tvm_shouJieSuan_waitSubmit);
        return page;
    }


    /**
     * tvm已经提交的
     * @param page
     * @param param
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getXw_tvm_shouJieSuan_areadySubmit")
    @ApiOperation(value = "tvm已经提交的", notes = "tvm已经提交的")
    public Page getXw_tvm_shouJieSuan_areadySubmit(Page page, @RequestParam Map<String,String> param) throws ParseException {
        List<Map<String,Object>> swStTvmIncomeSettles = swStTvmIncomeSettleMapper.selectSwStTvmIncomeSettle(param);
        page.setData(swStTvmIncomeSettles);
        return page;
    }
    /**
     * 钱箱卸载后更新收入结算清点金额、现金实收金额
     * @return
     * @throws SQLException
     */
    @RequestMapping("/updateUnAmount")
    @Inner
    @Transactional(rollbackFor = Exception.class)
    public Result updateUnAmount(@RequestBody SwStTvmIncomeSettle swStTvmIncomeSettleDto ) {
        Result res=new Result(ResultDetailMsg.OK);
        try {
            SwStTvmIncomeSettle swStTvmIncomeSettle = swStTvmIncomeSettleMapper.selectOne(Wrappers.<SwStTvmIncomeSettle>lambdaQuery()
                    .eq(SwStTvmIncomeSettle::getLineCode, swStTvmIncomeSettleDto.getLineCode())
                    .eq(SwStTvmIncomeSettle::getStationCode, swStTvmIncomeSettleDto.getStationCode())
                    .eq(SwStTvmIncomeSettle::getTvmCode, swStTvmIncomeSettleDto.getTvmCode())
                    .eq(SwStTvmIncomeSettle::getRecordTime, swStTvmIncomeSettleDto.getRecordTime())
                    .eq(SwStTvmIncomeSettle::getDelFlag,"0"));
            if(ObjectUtil.isNotEmpty(swStTvmIncomeSettle)){
                swStTvmIncomeSettle.setCheckAmount(swStTvmIncomeSettleDto.getCheckAmount());//清点金额
                swStTvmIncomeSettle.setCashReceiptAmount(swStTvmIncomeSettleDto.getCashReceiptAmount());//现金实收金额
                swStTvmIncomeSettle.setUpdateTime(new Date());//修改时间
                swStTvmIncomeSettleMapper.updateById(swStTvmIncomeSettle);
            }
        } catch (Exception e) {
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("修改失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return res;
    }

    /**
     * 预览数据
     * @param param
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getXw_tvm_shouJieSuan_preview")
    @ApiOperation(value = "预览数据", notes = "预览数据")
    public Result getXw_tvm_shouJieSuan_preview(@RequestParam Map<String,Object> param) throws SQLException, ParseException {
        Result res=new Result(ResultDetailMsg.OK);
        List<Map<String, Object>> tvm_preview = TvmUtil.get_tvm_preview(param);
        res.setData(tvm_preview);
        return res;
    }

    /**
     * tvm长周期结算
     * @param param
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getXw_tvm_long_js")
    @ApiOperation(value = "tvm长周期结算", notes = "tvm长周期结算")
    public Result getXw_tvm_long_js(@RequestParam Map<String,String> param) throws ParseException {
        Result res=new Result(ResultDetailMsg.OK);
        List<SwAuTvmBoxAmountDifference> swAuTvmBoxAmountDifferences = xwShouJieSuanMapper.getXw_tvm_long_js(param);
        res.setData(swAuTvmBoxAmountDifferences);
        return res;
    }

    /**
     * tvm收入结算提交
     * @param params
     * @return
     * @throws ParseException
     */
    @RequestMapping("/submit_Xw_tvm_data")
    @ApiOperation(value = "tvm收入结算提交", notes = "tvm收入结算提交")
    @Transactional(rollbackFor = Exception.class)
//    public Result submit_Xw_tvm_data(@RequestParam Map<String,Object> params,@RequestParam(defaultValue = "false") Boolean isReport) throws ParseException {
    public Result submit_Xw_tvm_data(@RequestBody JSONObject params) throws ParseException {
        Result res = new Result(ResultDetailMsg.OK);
        String md5 = MD5.create().digestHex(params.toString());
        if (noPass(SecurityUtils.getUser().getId(), "tvmSubmit", md5)) {
            res.setMsg("请勿重复提交");
            return res;
        }
        try {
            String s = (String) params.get("rows");
            JSONArray jsArr = JSONArray.parseArray(s);
            for(int i=0;i<jsArr.size();i++){
                JSONObject jsonObject = jsArr.getJSONObject(i);
                Boolean isReport = params.getBoolean("isReport"); isReport=isReport==null?false:isReport;
                Boolean isLong = params.getBoolean("isLong"); isLong=isLong==null?false:isLong;
                if(isLong){
                    jsonObject.put("js_startSettleDate",params.get("startSettleDate"));
                    jsonObject.put("js_endSettleDate",params.get("endSettleDate"));
                }
                Integer integer = TvmSqlUpdate.insertSW_ST_TVM_INCOME_SETTLE(params,jsonObject); //添加收入结算表
                if(integer==0){
                    throw new Exception("添加收入结算表出错");
                }
                Integer integer1 = TvmSqlUpdate.insert_sw_au_tvm_amount_defference(params,jsonObject);//插入审核主表
                if(integer1==0){
                    throw new Exception("插入审核主表出错");
                }
                Integer integer2 = TvmSqlUpdate.insert_sw_au_tvm_box_amount_difference(params,jsonObject);//插入审核分钱箱主表
                if(integer2==0){
                    throw new Exception("插入审核分钱箱主表出错");
                }
                boolean b = writeLongPERIOD_SETTLE_LOG(jsonObject,params);
                if(!b){
                    throw new Exception("添加长周期日志跟踪表出错");
                }
                boolean b1 = updateStatusSubmitStatus(jsonObject,params);
                if(!b1){
                    throw new Exception("修改状态出错");
                }
                //TODO 不适用了
//                if(isReport){
//                    TvmUtil.updateReportAlert("车站TVM日结账单",jsonObject.getString("revenueTime"));//修改报表名
//                }
            }
        } catch (Exception e) {
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("提交失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //platformTransactionManager.rollback(TransactionAspectSupport.currentTransactionStatus());
        }finally {
//            platformTransactionManager.commit(TransactionAspectSupport.currentTransactionStatus());//手动提交事务
        }
        return res;
    }

    /**
     * 提交报表差错
     * @param params
     * @return
     * @throws ParseException
     */
    @RequestMapping("/submit_Xw_tvm_reportError_data")
    @ApiOperation(value = "提交报表差错", notes = "提交报表差错")
    @Transactional(rollbackFor = Exception.class)
   // public Result submit_Xw_tvm_reportError_data(@RequestParam Map<String,Object> params,String attendancePersonJobNo,@RequestParam(defaultValue = "false") Boolean isLong,@RequestParam(defaultValue = "false") Boolean isReport) throws ParseException {
    public Result submit_Xw_tvm_reportError_data(@RequestBody JSONObject params) throws ParseException {

        Result res = new Result(ResultDetailMsg.OK);
        String md5 = MD5.create().digestHex(params.toString());
        if (noPass(SecurityUtils.getUser().getId(), "tvmSubmit", md5)) {
            res.setMsg("请勿重复提交");
            return res;
        }
        try {
            String attendancePersonJobNo=params.getString("attendancePersonJobNo");
            Boolean isLong=params.getBoolean("isLong"); isLong=isLong==null?false:isLong;
            Boolean isReport=params.getBoolean("isReport");isReport=isReport==null?false:isReport;

            String s = (String) params.get("rows");
            JSONArray jsArr = JSONArray.parseArray(s);
            for(int i=0;i<jsArr.size();i++){
                JSONObject jsonObject = jsArr.getJSONObject(i);
                JSONObject p=new JSONObject();
                p.put("ids",jsonObject.getString("id"));
                p.put("startSettleDate",jsonObject.getString("js_startSettleDate"));
                p.put("endSettleDate",jsonObject.getString("js_endSettleDate"));
                p.put("js_startSettleDate",jsonObject.getString("js_startSettleDate"));
                p.put("js_endSettleDate",jsonObject.getString("js_endSettleDate"));
                p.put("lineCode",jsonObject.getString("lineCode"));
                p.put("stationCode",jsonObject.getString("stationCode"));
                p.put("tvmCode",jsonObject.getString("tvmCode"));
                p.put("attendancePersonJobNo",attendancePersonJobNo);


                Integer integer = TvmReportErrorSqlUpdate.insertSW_ST_TVM_INCOME_SETTLE(p); //添加收入结算表
                if(integer==0){
                    throw new Exception("添加收入结算表出错");
                }
                Integer integer1 = TvmReportErrorSqlUpdate.insert_sw_au_tvm_amount_defference(p);//插入审核主表
                if(integer1==0){
                    throw new Exception("插入审核主表出错");
                }
                Integer integer2 = TvmReportErrorSqlUpdate.insert_sw_au_tvm_box_amount_difference(p);//插入审核分钱箱主表
                if(integer2==0){
                    throw new Exception("插入审核分钱箱主表出错");
                }


                boolean b = writeLongPERIOD_SETTLE_LOG(jsonObject,p);
                if(!b){
                    throw new Exception("添加长周期日志跟踪表出错");
                }
                boolean b1 = updateStatusSubmitStatus(jsonObject,p);
                if(!b1){
                    throw new Exception("修改状态出错");
                }

                boolean up1 = updateReportDatas(jsonObject);
                if(!up1){
                    throw new Exception("更新报表差错数据出错");
                }
                //TODO 不适用了
//                if(isReport){
//                    TvmUtil.updateReportAlert("车站TVM日结账单",jsonObject.getString("revenueTime"));//修改报表名
//                }
            }
        } catch (Exception e) {
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("提交失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }finally {
        }
        return res;
    }

    /**
     * 长周期结算日志跟踪表
     * @param js
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean writeLongPERIOD_SETTLE_LOG(JSONObject js,Map<String,Object> params){
        try {
            SwStLongperiodSettleLog swStLongperiodSettleLog=new SwStLongperiodSettleLog();
            swStLongperiodSettleLog.setLineCode(js.getString("lineCode"));
            swStLongperiodSettleLog.setStationCode(js.getString("stationCode"));
            swStLongperiodSettleLog.setDeviceNo(js.getString("tvmCode"));
            swStLongperiodSettleLog.setDeviceType("1");


            QueryWrapper<SwStLongperiodSettleLog> queryWrapper=new QueryWrapper<>();
            queryWrapper.setEntity(swStLongperiodSettleLog);
            List<SwStLongperiodSettleLog> swStLongperiodSettleLogs = swStLongperiodSettleLogMapper.selectList(queryWrapper);
            if(swStLongperiodSettleLogs.size()>0){
                swStLongperiodSettleLog=swStLongperiodSettleLogs.get(0);
            }
            swStLongperiodSettleLog.setConductorJobNo(js.getString("operatorJobNo")==null?"":js.getString("operatorJobNo"));

//            Date settleStartTime = DateFormat.panDuanDate(params.get("startSettleDate"));
//            Date settleEndTime = DateFormat.panDuanDate(params.get("endSettleDate"));

            Date settleStartTime = DateFormat.panDuanDate(js.get("js_startSettleDate"));
            Date settleEndTime = DateFormat.panDuanDate(js.get("js_endSettleDate"));

            swStLongperiodSettleLog.setBeginSettleDate(settleStartTime);
            swStLongperiodSettleLog.setEndSettleDate(settleEndTime);
            swStLongperiodSettleLog.setSettleDate(new Date());
            long l = (settleEndTime.getTime() - settleStartTime.getTime()) / (24 * 60 * 60 * 1000)+1;
            swStLongperiodSettleLog.setSettlePeriod(Integer.parseInt(l+""));
            swStLongperiodSettleLog.setSettlePersonId(UserInfo.getId());
            swStLongperiodSettleLog.setSettlePerson(UserInfo.getUserName());
            swStLongperiodSettleLog.setSettlePersonJobNo(UserInfo.getUserCode());
            swStLongperiodSettleLog.setUpdateTime(new Date());

            if(swStLongperiodSettleLogs.size()>0){
                swStLongperiodSettleLogMapper.updateById(swStLongperiodSettleLog);
            }else{
                swStLongperiodSettleLog.setCreatorId(UserInfo.getId());
                swStLongperiodSettleLog.setCreateTime(new Date());
                swStLongperiodSettleLog.setCreatorName(UserInfo.getUserName());
                int ref=swStLongperiodSettleLogMapper.insertSwStLongperiodSettleLog(swStLongperiodSettleLog);
            }
        }catch (Exception e){
            log.error("{}",e);
            return false;
        }
        return true;
    }

//
//    private boolean insertSwAuItvmOnlineAmountHierarchyDifference(JSONObject param,Integer id,Integer settleId) throws ParseException, SQLException, IllegalAccessException {
//        SwAuItvmOnlineAmountHierarchyDifference swAuItvmOnlineAmountHierarchyDifference=new SwAuItvmOnlineAmountHierarchyDifference();
//        swAuItvmOnlineAmountHierarchyDifference.setRelationSourceId(id);
//        swAuItvmOnlineAmountHierarchyDifference.setLineCode(param.getString("lineCode"));
//        swAuItvmOnlineAmountHierarchyDifference.setStationCode(param.getString("stationCode"));
//        swAuItvmOnlineAmountHierarchyDifference.setTvmOrder(param.getString("tvmCode"));
//
//        Date revenueTime =TvmUtil.panDuanDate(param.getString("revenueTime"));
//        swAuItvmOnlineAmountHierarchyDifference.setSettleTime(revenueTime);
//        swAuItvmOnlineAmountHierarchyDifference.setType("1");
//
//        QueryWrapper<SwAuItvmOnlineAmountHierarchyDifference> queryWrapper=new QueryWrapper<>();
//        queryWrapper.setEntity(swAuItvmOnlineAmountHierarchyDifference);
//        List<SwAuItvmOnlineAmountHierarchyDifference> swAuItvmOnlineAmountHierarchyDifferences = swAuItvmOnlineAmountHierarchyDifferenceMapper.selectList(queryWrapper);
//        if(swAuItvmOnlineAmountHierarchyDifferences.size()>0){
//            swAuItvmOnlineAmountHierarchyDifference=swAuItvmOnlineAmountHierarchyDifferences.get(0);
//        }
//
//        Map<String, BigDecimal> jieZhangDanJu = TvmUtil.getJieZhangDanJu(param);
//        swAuItvmOnlineAmountHierarchyDifference.setDepositAmount(jieZhangDanJu.get("rechargeMoney"));
//        swAuItvmOnlineAmountHierarchyDifference.setSaleAmount(jieZhangDanJu.get("sellTicketMoney"));
//        swAuItvmOnlineAmountHierarchyDifference.setErrorRefundAmount(jieZhangDanJu.get("faultRefundAmount"));
//
//        swAuItvmOnlineAmountHierarchyDifference.setAssistStatus("1");
//        swAuItvmOnlineAmountHierarchyDifference.setReplaceStatus("0");
//        swAuItvmOnlineAmountHierarchyDifference.setDataType("1");
//        swAuItvmOnlineAmountHierarchyDifference.setCreatorId(UserInfo.getId());
//        swAuItvmOnlineAmountHierarchyDifference.setCreateTime(new Date());
//
//        swAuItvmOnlineAmountHierarchyDifference=(SwAuItvmOnlineAmountHierarchyDifference) ObejctFieldsValueNotNull.jisuanBigDicmalMulti(SwAuItvmOnlineAmountHierarchyDifference.class,swAuItvmOnlineAmountHierarchyDifference,100d);
//
//        if(swAuItvmOnlineAmountHierarchyDifferences.size()>0){
//            swAuItvmOnlineAmountHierarchyDifferenceMapper.updateById(swAuItvmOnlineAmountHierarchyDifference);
//        }else{
//            swAuItvmOnlineAmountHierarchyDifferenceMapper.insert(swAuItvmOnlineAmountHierarchyDifference);
//        }
//        return true;
//    }

    /**
     * 修改提交状态
     * @param js
     * @param params
     * @return
     * @throws SQLException
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatusSubmitStatus(JSONObject js,Map<String,Object> params) throws SQLException {
//        Object startSettleDate = params.get("startSettleDate");
//        Object endSettleDate = params.get("endSettleDate");
        Object startSettleDate = js.get("js_startSettleDate");
        Object endSettleDate = js.get("js_endSettleDate");
        try {
            JdbcUtil.exeSqlCrud("update sw_st_tvm_check_detail set approval_status='1',REPORT_MODIFY_STATUS='0' where id="+js.getString("id"));
//            JdbcUtil.exeSqlCrud("update sw_st_tvm_check_detail set approval_status=1 where line_code='"+js.getString("lineCode")+"' and station_code='"+js.getString("stationCode")+"' and tvm_code='"+js.getString("tvmCode")+"' and revenue_time='"+js.getString("revenueTime")+"'");
            JdbcUtil.exeSqlCrud("update sw_st_handwork_clean_record set approval_status='1',REPORT_MODIFY_STATUS='0' where DEL_FLAG='0' and  line_code='"+js.getString("lineCode")+"' and station_code='"+js.getString("stationCode")+"' and clean_time between '"+startSettleDate+"' and '"+endSettleDate+"'");
            //JdbcUtil.exeSqlCrud("update sw_st_tvm_daily_bill set approval_status='1',REPORT_MODIFY_STATUS='0' where line_code='"+js.getString("lineCode")+"' and station_code='"+js.getString("stationCode")+"' and tvm_code='"+js.getString("tvmCode")+"' and (start_time between '"+startSettleDate+"' and '"+endSettleDate+"') and (end_time between '"+startSettleDate+"' and '"+endSettleDate+"')");
            JdbcUtil.exeSqlCrud("update sw_st_tvm_supplement_currency set approval_status='1',REPORT_MODIFY_STATUS='0' where DEL_FLAG='0' and  line_code='"+js.getString("lineCode")+"' and station_code='"+js.getString("stationCode")+"' and supplement_currency_time between '"+startSettleDate+"' and '"+endSettleDate+"'");
            JdbcUtil.exeSqlCrud("update sw_st_input_cashbox_uninstalled set is_submit=1 where DEL_FLAG='0' and  line_code='"+js.getString("lineCode")+"' and station_code='"+js.getString("stationCode")+"' and tvm_code='"+js.getString("tvmCode")+"' and del_flag = 0 " +
                    "and uninstall_date between date_format('"+startSettleDate+"','%Y-%m-%d') and date_format('"+endSettleDate+"','%Y-%m-%d') ");
        }catch (Exception e) {
            log.error("{}",e);
            return false;
        }
        return true;
    }

    /**
     * 修改报表差错更改申请 是否修改状态
     * @param js
     * @return
     */
    public boolean updateReportDatas(JSONObject js)  {
        String lineCode = js.getString("lineCode");
        String stationCode = js.getString("stationCode");
        String tvmCode = js.getString("tvmCode");
        Object reprotTime = js.get("revenueTime");
        QueryWrapper<SwStReportErrorAlterApply> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SwStReportErrorAlterApply::getLineCode,lineCode)
                .eq(SwStReportErrorAlterApply::getStationCode,stationCode)
                .eq(SwStReportErrorAlterApply::getReprotTime,reprotTime)
                .in(SwStReportErrorAlterApply::getReportNameId,"5","6","7")
			    .ne(SwStReportErrorAlterApply::getIsModify,"1")
			    .ne(SwStReportErrorAlterApply::getCheckStatus,"4")
                .eq(SwStReportErrorAlterApply::getDelFlag,"0");
        List<SwStReportErrorAlterApply> listReport = swStReportErrorAlterAppayMapper.selectList(wrapper);
        List<SwStReportErrorAlterApply> listReportReturn = listReport.stream().filter(x->{
            if("5".equals(x.getReportNameId())&& !Objects.equals(x.getTvmCode(),tvmCode)){
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        listReportReturn.forEach(item->{
            QueryWrapper<SwStReportErrorAlterApply> wrappers = new QueryWrapper<>();
            wrappers.lambda().eq(SwStReportErrorAlterApply::getId,item.getId());
            SwStReportErrorAlterApply swStReportErrorAlterApply = new SwStReportErrorAlterApply();
            swStReportErrorAlterApply.setIsModify("1");
            swStReportErrorAlterApply.setModifyTime(new Date());
            swStReportErrorAlterAppayMapper.update(swStReportErrorAlterApply,wrappers);
        });
        return true;
    }

	/**
     * 查询是否有待确认数据
     * @param param
     * @return
     * @throws SQLException
     */
    @RequestMapping("/getTvmNotConfirmDatas")
    @ApiOperation(value = "查询是否有待确认数据", notes = "查询是否有待确认数据")
    public Result getTvmNotConfirmDatas(@RequestParam Map<String,Object> param) throws SQLException {
        Result res=new Result(ResultDetailMsg.OK);
        try {
            JSONObject tvmNotConfirmData = TvmUtil.getTvmNotConfirmData(param);
            res.setData(tvmNotConfirmData);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            res.setMsg("查询出错");
        }
        return res;
    }

	/**
     * 查询是否正在做自动提交
     * @return
     * @throws SQLException
     */
    @RequestMapping("/getAutoSubmitFlag")
    @ApiOperation(value = "查询是否正在做自动提交", notes = "查询是否正在做自动提交")
    public Result getTvmNotConfirmDatas(String lineCode,String stationCode) throws SQLException {
        Result res=new Result(ResultDetailMsg.OK);
        try {
            boolean isRunning = TvmUtil.isRunningAutoSubmit(lineCode,stationCode);
            res.setData(isRunning);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            res.setMsg("查询出错");
        }
        return res;
    }


    /**
     * 收入结算TVM补提交页面查询
     * @param page
     * @param param
     * @return
     * @throws SQLException
     */
    @RequestMapping("/getShouJieSuanRepairSubmit")
    @ApiOperation(value = "收入结算TVM补提交页面查询", notes = "收入结算TVM补提交页面查询")
    public Page getShouJieSuanRepairSubmit(Page page, @RequestParam Map<String,String> param) throws SQLException {
        List<Map<String, Object>> tvm_shouJieSuan_waitSubmit = TvmUtil.getShouJieSuanRepairSubmit(param);
        List<Map<String, Object>> s = tvm_shouJieSuan_waitSubmit.stream().filter(x -> org.springframework.util.StringUtils.isEmpty(x.get("preSubmitDate"))).collect(Collectors.toList());
        s.stream().map(object -> {
            try {
                if(object.containsKey("preSubmitDate")){
                    Object revenueTime = object.get("revenueTime");
                    Date preSubmitDate = DateFormat.panDuanDate(revenueTime);//利用Calendar 实现 Date日期-1天
                    Calendar c = Calendar.getInstance();
                    if(preSubmitDate!=null){
                        c.setTime(preSubmitDate);
                        c.add(Calendar.DAY_OF_MONTH, -1);
                        preSubmitDate = c.getTime();
                    }
                    String preDate = DateFormat.date_ex_str(preSubmitDate);
                    object.put("preSubmitDate",preDate);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return  object;
        }).collect(Collectors.toList());
        page.setData(tvm_shouJieSuan_waitSubmit);
        return page;
    }

    /**
     * 收入结算TVM补提交查询结算周期
     * @param
     * @param param
     * @return
     * @throws SQLException
     */
    @RequestMapping("/getPeriods")
    @ApiOperation(value = "收入结算TVM补提交查询结算周期", notes = "收入结算TVM补提交查询结算周期")
    public Map<String,Object> getPeriods(@RequestParam Map<String,String> param) throws SQLException, ParseException {
        List<Map<String, Object>> tvm = TvmUtil.getPeriods(param);
        Map<String,Object> ss = new HashMap<>();
        String revenueTime=param.get("revenueTime");
        if(tvm.size()>0){
            return tvm.get(0);
        }else {//TVM结算补提考虑长周期车站提交获取结算周期在sw_ck_data_submit_log获取不到时结算周期计算的问题
            List<Map<String, Object>> periodsDay = TvmUtil.getPeriodsDay(param);
            if(periodsDay.size()>0){//长周期车站根据结算天数计算结算周期
                String tvmSettlementTerm = String.valueOf(periodsDay.get(0).get("tvmSettlementTerm"));
                //长周期车站结算周期天数
                int day = Integer.parseInt(tvmSettlementTerm);
                Date startTimeD=DateFormat.stringToDate(revenueTime);
                Date endTimeD=DateFormat.stringToDate(revenueTime);
                //获取revenueTime对应月份的总天数
                int days = DateFormat.dayByMonth(startTimeD);
                //获取revenueTime对应月份的最后一天日期
                Date  lastDay = DateFormat.getLastDayOfMonth(startTimeD);
                String beginTime,endTime;
                //长周期车站提交月底数据获取结算周期在sw_ck_data_submit_log获取不到时计算结算周期
                if(days%day !=0 && lastDay.compareTo(startTimeD) == 0){
                    if(days%day == 2){
                        //利用Calendar 实现 Date日期-结算周期天数
                        Calendar c = Calendar.getInstance();
                        c.setTime(startTimeD);
                        c.add(Calendar.DAY_OF_MONTH, -1);
                        startTimeD = c.getTime();
                        beginTime = DateFormat.date_ex_str(startTimeD);
                        endTime = DateFormat.date_ex_str(endTimeD);
                    }else if(days%day == 3){
                        //利用Calendar 实现 Date日期-结算周期天数
                        Calendar c = Calendar.getInstance();
                        c.setTime(startTimeD);
                        c.add(Calendar.DAY_OF_MONTH, -2);
                        startTimeD = c.getTime();
                        beginTime = DateFormat.date_ex_str(startTimeD);
                        endTime = DateFormat.date_ex_str(endTimeD);
                    }else{
                        beginTime = DateFormat.date_ex_str(startTimeD);
                        endTime = DateFormat.date_ex_str(endTimeD);
                    }
                }else{
                    int period = Integer.parseInt(tvmSettlementTerm)-1;
                    //利用Calendar 实现 Date日期-结算周期天数
                    Calendar c = Calendar.getInstance();
                    c.setTime(startTimeD);
                    c.add(Calendar.DAY_OF_MONTH, -period);
                    startTimeD = c.getTime();
                    beginTime = DateFormat.date_ex_str(startTimeD);
                    endTime = DateFormat.date_ex_str(endTimeD);
                }
                ss.put("beginTime",beginTime);
                ss.put("endTime",endTime);
            }else {//非长周期车站
                Date startTimeD=DateFormat.stringToDate(revenueTime);
                Date endTimeD=DateFormat.stringToDate(revenueTime);
                String beginTime = DateFormat.date_ex_str(startTimeD);
                String endTime = DateFormat.date_ex_str(endTimeD);
                ss.put("beginTime",beginTime);
                ss.put("endTime",endTime);
            }
            return ss;
        }
    }

    /**
     * TVM收入结算补提交
     * @param params
     * @return
     */
    @RequestMapping("/repairSubmitXwTvmData")
    @ApiOperation(value = "TVM收入结算补提交", notes = "TVM收入结算补提交")
    @Transactional(rollbackFor = Exception.class)
    public Result repairSubmitXwTvmData(@RequestBody JSONObject params) {//List<Integer> idList,String startSettleDate,String endSettleDate
        Result res = new Result(ResultDetailMsg.OK);
        //List<Integer> idList = params.get("idList");
        JSONArray idList = params.getJSONArray("idList");
        String startSettleDate = params.getString("startSettleDate");
        String endSettleDate = params.getString("endSettleDate");
        String attendancePersonJobNo= SecurityUtils.getUser().getUserCode();
        JSONObject jsonObject = new JSONObject();
        try {
            Date startTimeD=DateFormat.stringToDate(startSettleDate);
            Date endTimeD=DateFormat.stringToDate(endSettleDate);
            //利用Calendar 实现 Date日期+1天
            Calendar c = Calendar.getInstance();
            c.setTime(endTimeD);
            c.add(Calendar.DAY_OF_MONTH, 1);
            endTimeD = c.getTime();
            String startTime = DateFormat.date_ex_str(startTimeD)+" 02:00:00";
            String endTime = DateFormat.date_ex_str(endTimeD)+" 01:59:59";
            jsonObject.put("startTime",startTime);
            jsonObject.put("endTime",endTime);
            jsonObject.put("attendancePersonJobNo",attendancePersonJobNo);
            for(int i=0;i<idList.size();i++){
                JSONObject jsons = idList.getJSONObject(i);
            //for(Integer id : idList){
                SwStTvmCheckDetail tvmCheckDetail = swStTvmCheckDetailMapper.selectById(jsons.getInteger("id"));
                //JSONObject jsonObject = new JSONObject();
                if(tvmCheckDetail!=null){
                    /*Date endTimeD=DateFormat.LocalDateToUdate(tvmCheckDetail.getRevenueTime());
                    //利用Calendar 实现 Date日期+1天
                    Calendar c = Calendar.getInstance();
                    c.setTime(endTimeD);
                    c.add(Calendar.DAY_OF_MONTH, 1);
                    endTimeD = c.getTime();
                    String startTime = DateFormat.LocalDateTurnString(tvmCheckDetail.getRevenueTime())+" 02:00:00";
                    String endTime = DateFormat.date_ex_str(endTimeD)+" 01:59:59";
                    jsonObject.put("startTime",startTime);
                    jsonObject.put("endTime",endTime);
                    jsonObject.put("attendancePersonJobNo",attendancePersonJobNo);*/
                    //添加收入结算表
                    Integer integer = TvmSqlUpdate.insertTvmIncomeSettleRepair(tvmCheckDetail,jsonObject);
                    if(integer==0){
                        throw new Exception("添加收入结算表出错");
                    }
                    Integer integer1 = TvmSqlUpdate.insertAuTvmAmountDefference(tvmCheckDetail,jsonObject);//插入审核主表
                    if(integer1==0){
                        throw new Exception("插入审核主表出错");
                    }
                    Integer integer2 = TvmSqlUpdate.insertAutvmBoxAmountDifference(tvmCheckDetail,jsonObject);//插入审核分钱箱主表
                    if(integer2==0){
                        throw new Exception("插入审核分钱箱主表出错");
                    }
                    boolean b = writeLongPeriodSettleLogRepair(jsonObject,tvmCheckDetail);
                    if(!b){
                        throw new Exception("添加长周期日志跟踪表出错");
                    }
                    boolean b1 = updateRepairStatusSubmitStatus(tvmCheckDetail,jsonObject);
                    if(!b1){
                        throw new Exception("修改状态出错");
                    }
                    boolean up1 = updateReportDatas(jsons);
                    if(!up1){
                        throw new Exception("更新报表差错数据出错");
                    }
                }

            }
        } catch (Exception e) {
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("提交失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }finally {
        }
        return res;
    }

    /**
     * 修改提交状态
     * @param tvmCheckDetail
     * @param js
     * @return
     * @throws SQLException
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRepairStatusSubmitStatus(SwStTvmCheckDetail tvmCheckDetail,JSONObject js) throws SQLException {
        Integer id = tvmCheckDetail.getId();
        String lineCode = tvmCheckDetail.getLineCode();
        String stationCode = tvmCheckDetail.getStationCode();
        String tvmCode = tvmCheckDetail.getTvmCode();
        Object startSettleDate = js.get("startTime");
        Object endSettleDate = js.get("endTime");
        try {
            JdbcUtil.exeSqlCrud("update sw_st_tvm_check_detail set approval_status='1',REPORT_MODIFY_STATUS='0' where id="+id);
            JdbcUtil.exeSqlCrud("update sw_st_handwork_clean_record set approval_status='1',REPORT_MODIFY_STATUS='0' where DEL_FLAG='0' and line_code='"+lineCode+"' and station_code='"+stationCode+"' and clean_time between '"+startSettleDate+"' and '"+endSettleDate+"'");
            JdbcUtil.exeSqlCrud("update sw_st_tvm_supplement_currency set approval_status='1',REPORT_MODIFY_STATUS='0' where DEL_FLAG='0' and line_code='"+lineCode+"' and station_code='"+stationCode+"' and supplement_currency_time between '"+startSettleDate+"' and '"+endSettleDate+"'");
            JdbcUtil.exeSqlCrud("update sw_st_input_cashbox_uninstalled set is_submit=1 where DEL_FLAG='0' and  line_code='"+lineCode+"' and station_code='"+stationCode+"' and tvm_code='"+tvmCode+"' and del_flag = 0 " +
                    "and uninstall_date between date_format('"+startSettleDate+"','%Y-%m-%d') and date_format('"+endSettleDate+"','%Y-%m-%d') ");
        }catch (Exception e) {
            log.error("{}",e);
            return false;
        }
        return true;
    }

    /**
     * 新增或修改长周期结算日志跟踪表
     * @param js
     * @param tvmCheckDetail
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean writeLongPeriodSettleLogRepair(JSONObject js,SwStTvmCheckDetail tvmCheckDetail){
        try {
            SwStLongperiodSettleLog swStLongperiodSettleLog=new SwStLongperiodSettleLog();
            swStLongperiodSettleLog.setLineCode(tvmCheckDetail.getLineCode());
            swStLongperiodSettleLog.setStationCode(tvmCheckDetail.getStationCode());
            swStLongperiodSettleLog.setDeviceNo(tvmCheckDetail.getTvmCode());
            swStLongperiodSettleLog.setDeviceType("1");
            QueryWrapper<SwStLongperiodSettleLog> queryWrapper=new QueryWrapper<>();
            queryWrapper.setEntity(swStLongperiodSettleLog);
            List<SwStLongperiodSettleLog> swStLongperiodSettleLogs = swStLongperiodSettleLogMapper.selectList(queryWrapper);
            if(swStLongperiodSettleLogs.size()>0){
                swStLongperiodSettleLog=swStLongperiodSettleLogs.get(0);
            }
            swStLongperiodSettleLog.setConductorJobNo(tvmCheckDetail.getCheckPersonTwoJopNo()==null?"":tvmCheckDetail.getCheckPersonTwoJopNo());
            Date settleStartTime = DateFormat.panDuanDate(js.get("startTime"));
            Date settleEndTime = DateFormat.panDuanDate(js.get("endTime"));
            swStLongperiodSettleLog.setBeginSettleDate(settleStartTime);
            swStLongperiodSettleLog.setEndSettleDate(settleEndTime);
            swStLongperiodSettleLog.setSettleDate(new Date());
            long l = (settleEndTime.getTime() - settleStartTime.getTime()) / (24 * 60 * 60 * 1000)+1;
            swStLongperiodSettleLog.setSettlePeriod(Integer.parseInt(l+""));
            swStLongperiodSettleLog.setSettlePersonId(UserInfo.getId());
            swStLongperiodSettleLog.setSettlePerson(UserInfo.getUserName());
            swStLongperiodSettleLog.setSettlePersonJobNo(UserInfo.getUserCode());
            swStLongperiodSettleLog.setUpdateTime(new Date());
            if(swStLongperiodSettleLogs.size()>0){
                swStLongperiodSettleLogMapper.updateById(swStLongperiodSettleLog);
            }else{
                swStLongperiodSettleLog.setCreatorId(UserInfo.getId());
                swStLongperiodSettleLog.setCreateTime(new Date());
                swStLongperiodSettleLog.setCreatorName(UserInfo.getUserName());
                int ref=swStLongperiodSettleLogMapper.insertSwStLongperiodSettleLog(swStLongperiodSettleLog);
            }
        }catch (Exception e){
            log.error("{}",e);
            return false;
        }
        return true;
    }

    @Override
    public RedisTemplate<String, String> redisTemplate() {
        return redisTemplate;
    }
}
